//
//  StatusPictureView.swift
//  SinaWeibo
//
//  Created by 张子国 on 15/11/17.
//  Copyright © 2015年 张子国. All rights reserved.
//

import UIKit
import SnapKit
import SDWebImage
private let PictureCellId = "PictureCellId"

private let PictureCellMargin: CGFloat = 5

class StatusPictureView: UICollectionView {


    var imageUrls : [NSURL]? {
        didSet {
            print(imageUrls)
            
            //刷新数据
            self.reloadData()
            
            let viewSize = self.calceViewSize()
            self.snp_updateConstraints { (make) -> Void in
                make.width.equalTo(viewSize.width)
                make.height.equalTo(viewSize.height)
               
            }
            testLabel.text = "\(imageUrls?.count ?? 0)"
        }
    }
    
    //计算配图视图大小
    private func calceViewSize() ->CGSize {
        let colum : CGFloat = 3
        let maxWidth = screenW - 2 * StatusCellMargin
        
        //单个图片宽度
        let itemWidth = (maxWidth - 2 * PictureCellMargin) / colum
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        //设置cell大小
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        //没有图片
        let imageCount = imageUrls?.count ?? 0
        if imageCount == 0 {
            return CGSizeZero
        }
        //一张图片
        if imageCount == 1 {
            //获取单张缓存图片
            let key = imageUrls?.last?.absoluteString
            print(key)
            let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(key!)
            
//          let imageSize = CGSize(width: 180, height: 120)
//            var imageSize? =0
            if image == nil {
            let imageSize = CGSize(width: 180, height: 180)
         
                return imageSize
            } else {
            let imageSize = image.size
            layout.itemSize = imageSize
                return imageSize
            }
            
//            layout.itemSize = imageSize
//            return imageSize
        }
        //四张图片
        if imageCount == 4 {
            let w = itemWidth * 2 + PictureCellMargin
            layout.itemSize = CGSize(width: w, height: w)
            return CGSize(width: w, height: w)
        } else {
        //多张图片
        let row = CGFloat((imageCount - 1) / 3 + 1)
        let w = maxWidth
        let h = row * itemWidth + (row - 1) * PictureCellMargin
        //layout.itemSize = CGSize(width: w, height: h)
        return CGSize(width: w, height: h)
        }
    }
        init() {
        let layout = UICollectionViewFlowLayout()
        //设置layout
        layout.minimumInteritemSpacing = PictureCellMargin
        layout.minimumLineSpacing = PictureCellMargin
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        //注册cell
        registerClass(pictureCell.self, forCellWithReuseIdentifier: PictureCellId)
        
        //数据源代理
        dataSource = self
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: 设置UI
    private func setupUI() {
    backgroundColor = .randomColor()
    addSubview(testLabel)
    
    //设置布局
        testLabel.snp_makeConstraints { (make) -> Void in
            make.center.equalTo(self.snp_center)
        }
    }
    
   
    
    //MARK: 懒加载控件
    private lazy var testLabel : UILabel = {
        let l = UILabel()
        l.font = UIFont.systemFontOfSize(20)
        l.textColor = UIColor.redColor()
        l.sizeToFit()
        return l
    }()

}

extension StatusPictureView: UICollectionViewDataSource{
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return imageUrls?.count ?? 0
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let  cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! pictureCell
        cell.url = imageUrls![indexPath.item]
        
        return cell
    }
}

class pictureCell: UICollectionViewCell {
    var url: NSURL? {
        didSet {
            
          imageView.sd_setImageWithURL(url,placeholderImage: nil)
            
        }
    }
    
    //重写父类方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

   
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: 设置UI
    private func setupUI() {
        //添加子控件
        contentView .addSubview(imageView)
        //设置布局
        imageView.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        
    }
    //MARK: 懒加载控件
    //private lazy var imageView : UIImageView = UIImageView()
    private lazy var imageView : UIImageView = {
        let im = UIImageView()
        //图片样式
        im.contentMode = UIViewContentMode.ScaleAspectFill
        
        //手写代码，必须手动添加裁剪
        im.clipsToBounds = true
        return im
    }()
}

